package com.example.himalaya;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.example.himalaya.adapters.MainContentViewPagerAdapter;
import com.example.himalaya.adapters.NavigatorAdapter;
import com.example.himalaya.base.BaseActivity;
import com.example.himalaya.interfaces.IPlayerViewCallback;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.presenters.RecommendPresenter;
import com.example.himalaya.views.RoundRectImageView;
import com.google.android.material.navigation.NavigationView;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.util.List;

public class MainActivity extends BaseActivity implements IPlayerViewCallback {
    private static final String TAG = "MainActivity";
    private MagicIndicator mMainMagicIndicator;
    private ViewPager mMainContentViewPager;
    private NavigatorAdapter mNavigatorAdapter;
    private RoundRectImageView mMainTrackCoverIv;
    private TextView mMainTrackTitleTv;
    private TextView mMainTrackAuthorTv;
    private ImageView mMainPlayControlBtn;
    private PlayerPresenter mPlayerPresenter;
    private RecommendPresenter mRecommendPresenter;
    private View mMainToPlayer;
    private View mMainSearchBtn;
    private DrawerLayout mMainDrawerLayout;
    private Toolbar mMainToolbar;
    private NavigationView mMainNavView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initPresenter();
        initEvent();
    }


    private void initView() {
        //MagicIndicator魔术指示器
        mMainMagicIndicator = findViewById(R.id.main_magicIndicator);
        mMainMagicIndicator.setBackgroundColor(this.getResources().getColor(R.color.white));
        //创建CommonNavigator通用导航器并设置适配器
        CommonNavigator commonNavigator = new CommonNavigator(this);
        String[] indicatorTitles = getResources().getStringArray(R.array.main_magic_indicator_titles);
        mNavigatorAdapter = new NavigatorAdapter(this,indicatorTitles);
        commonNavigator.setAdapter(mNavigatorAdapter);
        //CommonNavigator通用导航器开启自我调节模式, 自动调整导航栏标题显示位置
        commonNavigator.setAdjustMode(true);
        //MagicIndicator魔术指示器设置导航器
        mMainMagicIndicator.setNavigator(commonNavigator);

        //ViewPager视图滑动页面-内容页面
        mMainContentViewPager = findViewById(R.id.main_content_viewPager);
        FragmentManager fragmentManager = getSupportFragmentManager();
        MainContentViewPagerAdapter viewPagerAdapter = new MainContentViewPagerAdapter(fragmentManager);
        mMainContentViewPager.setAdapter(viewPagerAdapter);

        //MagicIndicator魔术指示器和ViewPager视图滑动页面-内容页面绑定在一起
        ViewPagerHelper.bind(mMainMagicIndicator, mMainContentViewPager);

        mMainTrackCoverIv = findViewById(R.id.main_track_cover_Iv);
        mMainTrackTitleTv = findViewById(R.id.main_track_title_Tv);
        mMainTrackTitleTv.setSelected(true);
        mMainTrackAuthorTv = findViewById(R.id.main_track_author_Tv);
        mMainPlayControlBtn = findViewById(R.id.main_play_control_Btn);
        mMainToPlayer = findViewById(R.id.main_to_player);

        mMainSearchBtn = findViewById(R.id.main_search_Btn);

        mMainDrawerLayout = findViewById(R.id.main_drawer_layout);

        mMainToolbar = findViewById(R.id.main_toolbar);
        setSupportActionBar(mMainToolbar);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.icon_main_menu);
            actionBar.setDisplayShowTitleEnabled(false);
        }

        mMainNavView = findViewById(R.id.main_navigationView);
        mMainNavView.setItemIconTintList(null);//恢复图标的原来颜色
    }

    private void initPresenter() {
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallBack(this);
        mRecommendPresenter = RecommendPresenter.getRecommendPresenter();
    }

    private void initEvent() {
        mNavigatorAdapter.setOnIndicatorTitleClickListener(new NavigatorAdapter.OnIndicatorTitleClickListener() {
            @Override
            public void TitleClick(int index) {
                if (mMainContentViewPager != null) {
                    mMainContentViewPager.setCurrentItem(index, false);//false,去除ViewPager跳转的动画效果
                }
            }
        });
        mMainPlayControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayerPresenter != null) {
                    boolean hasPlayList = mPlayerPresenter.hasPlayList();
                    if (hasPlayList) {
                        if (mPlayerPresenter.isPlaying()) {
                            mPlayerPresenter.pause();
                        } else {
                            mPlayerPresenter.play();
                        }
                    } else {
                        //没有设置播放列表，默认播放第一个推荐专辑
                        playFirstRecommendAlbum();
                    }

                }
            }
        });

        mMainToPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到播放器界面
                if (mPlayerPresenter != null) {
                    boolean hasPlayList = mPlayerPresenter.hasPlayList();
                    if (hasPlayList) {
                        //跳转到播放器界面
                        Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
                        startActivity(intent);
                    } else {
                        //没有设置播放列表，默认播放第一个推荐专辑
                        playFirstRecommendAlbum();
                    }
                }
            }
        });

        mMainSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });

        mMainNavView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @SuppressLint("NonConstantResourceId")
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_main_my_menu_account:
                        Toast.makeText(MainActivity.this,"点击了我的账号",Toast.LENGTH_SHORT).show();
                        item.setChecked(false);
                        break;
                }
                mMainDrawerLayout.closeDrawers();
                return true;
            }
        });
    }

    /**
     * 播放第一个推荐专辑的内容
     */
    private void playFirstRecommendAlbum() {
        if (mRecommendPresenter != null) {
            List<Album> currentRecommendList = mRecommendPresenter.getCurrentRecommendList();
            if (currentRecommendList != null && currentRecommendList.size() > 0) {
                Album album = currentRecommendList.get(0);
                long albumId = album.getId();
                mPlayerPresenter.playByAlbumId(albumId);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mMainDrawerLayout.openDrawer(GravityCompat.START);
                break;
            default:
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallBack(this);
            mPlayerPresenter = null;
        }
    }


    //=====================播放器回调 开始========================

    @Override
    public void onPlayStart() {
        updatePlayControl(true);
    }

    private void updatePlayControl(boolean isPlaying) {
        if (mMainPlayControlBtn != null) {
            mMainPlayControlBtn.setImageResource(isPlaying ? R.drawable.selector_player_pause : R.drawable.selector_player_play);
        }
    }

    @Override
    public void onPlayPause() {
        updatePlayControl(false);
    }

    @Override
    public void onPlayStop() {
        updatePlayControl(false);
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onTrackListUI(List<Track> tracks) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode currentMode) {

    }

    @Override
    public void onProgressChange(int currentProgress, int totalDuration) {

    }

    @Override
    public void onAdLoading() {
        Toast.makeText(this,"请稍等,正在播放广告...",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onTrackUpdateUI(Track track, int index) {
        if (track != null) {
            String trackTitle = track.getTrackTitle();
            String nickname = track.getAnnouncer().getNickname();
            String coverUrlLarge = track.getCoverUrlLarge();
            if (mMainTrackCoverIv != null) {
                if (!TextUtils.isEmpty(coverUrlLarge)) {
                    Picasso.with(this).load(coverUrlLarge).into(mMainTrackCoverIv);
                } else {
                    Picasso.with(this).load(R.mipmap.logo).into(mMainTrackCoverIv);
                }
            }
            if (mMainTrackTitleTv != null) {
                mMainTrackTitleTv.setText(trackTitle);
            }
            if (mMainTrackAuthorTv != null) {
                mMainTrackAuthorTv.setText(nickname);
            }
        }
    }

    @Override
    public void onUpdatePlayListOrder(boolean isReverse) {

    }

    //=====================播放器回调 结束========================


}